package com.wili.c;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import com.c.Ca;
import com.wili.insertLog.BufferedLog;
/**
 * 
 * @author weila 2021-2-9
 */
public class LogObj implements BufferedLog {
	static int PrintTimeInterval = -1000;

	static final String DIR = C2.IsWindows ? "D:/bearJ/autoeq2/log" : "/usr/local/log/";

	final String name;

	final String DEBUG = "debug";

	final String WARN = "warn";

	final String ERROR = "error";

	final Logger loger;// = Logger.getLogger(Log4jObj.class);

	RollingFileAppender fileApp; 

	public LogObj(String name) { 
		this.name = name;
		++inc;
		ConsoleAppender conApp = null;
		switch (name) {
		case "":
			conApp = new ConsoleAppender(new PatternLayout("%m"));//原样输出
		case "console": {
			loger = Logger.getLogger("" + inc);//不同名称，避免log重复打印！
			loger.setAdditivity(false);//eg. 不继承来自log4j.properties的rootLog 
			if (conApp == null)
				conApp = new ConsoleAppender(new PatternLayout("%m%n"));//原样输出
			loger.addAppender(conApp);
			return;
		}
		case "root": {
			loger = Logger.getRootLogger();
			loger.setLevel(Level.ALL);
			WriterAppender app = new ConsoleAppender(new SimpleLayout());
			app.setName("");
			app.activateOptions();
			loger.addAppender(app);
			Class9.setFieldValue("name", null, loger);
			loger.getName();
			return;
		}
		default: {
			loger = Logger.getLogger(name + ":" + inc);
			loger.setAdditivity(false);//eg. 不继承来自log4j.properties的rootLog 
			String File_PATH = DIR + name + ".log";
			fileApp = new RollingFileAppender();
			fileApp.setFile(File_PATH);
			fileApp.setMaxBackupIndex(5);
			fileApp.setMaxFileSize("250MB");
			fileApp.setAppend(false);
			Layout layout;
			if ("".isEmpty()) {
				fileApp.setLayout(layout = new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN));//原样输出
			} else {
				fileApp.setLayout(layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN));
			}
			fileApp.activateOptions();
			//
			loger.addAppender(fileApp);
			//			Enumeration<?> en = loger.getAllAppenders();
			//			while (en.hasMoreElements()) {
			//				Object en2 = en.nextElement();
			//				System.out.println(en2);
			//			}
			return;
		}
		}
	}
	private long preTime;
	@Override
	public BufferedLog log(Object msg) {
		long curTime = System.currentTimeMillis();
		if (PrintTimeInterval > 0 && curTime - preTime > PrintTimeInterval) {
			preTime = curTime;
			loger.info("\n" + Date9.dateTimeStrOf(curTime));
		}
		if (++inc == 3)
			Ca.pause();
		if (msg != null && msg.toString().trim().isEmpty())
			Ca.pause();
		this.loger.info(msg);
		return this;
	}
	static int inc;
}